# -*- coding: utf-8 -*-
'''
Created on 2016年8月18日

@author: huanghaoyu
'''

from com.unitoll.test.http.http_client import HttpClient
from com.unitoll.test.utils.xml_utils import XmlUtils
import xmlunittest

URL = "http://128.8.50.233:8080/CommandGateway"
HEADERS = {'Content-Type': 'text/xml; charset=utf-8'}

def ignore_timestamp(xml):
    return XmlUtils.delTimestamp(xml)

def update_session_id(xml, new_session_id):
    return XmlUtils.setSessionId(xml, new_session_id)

def format_xml(xml_str):
    return XmlUtils.toPrettyXml(xml_str)

def test_business(excel_struct):
    session_id = None
    xml_test = xmlunittest.XmlTestMixin()
    is_all_equivalent = True
    for i in range(0, excel_struct.row_num):
        request_xml = excel_struct.get_cell_value(i, 0)
        
        if XmlUtils.isFirstRequest(request_xml.encode("utf-8")):
            response_xml = HttpClient.get_response_from_commandgateway(URL, HEADERS, request_xml)
            session_id = XmlUtils.getSessionId(response_xml)
        else:
            request_xml = update_session_id(request_xml, session_id)
            response_xml = HttpClient.get_response_from_commandgateway(URL, HEADERS, request_xml)
            
#         expected_response_xml = format_xml(update_session_id(excel_reader.get_cell_value_by_name(sheet_name, i, 1), session_id))
        expected_response_xml = update_session_id(excel_struct.get_cell_value(i, 1), session_id)
        
        try:
            xml_test.assertXmlEquivalentOutputs(data=ignore_timestamp(response_xml), 
                                                expected=ignore_timestamp(expected_response_xml))
        except AttributeError, e:
            # 由于 xmlunittest 模块的bug才要自己写这段
            print e
            print '\n'
            print 'Output are not equivalent:\nIn %d-th row in the %s business.\nSession ID: %s\nGiven:\n%s\nExpected:\n%s' % (i, excel_struct.sheet_name, session_id, format_xml(response_xml), format_xml(expected_response_xml))
            is_all_equivalent = False
    
    return is_all_equivalent

def test_businesses(excel_structs):
    is_all_equivalent = True
    for excel_struct in excel_structs:
        if test_business(excel_struct) is False:
            is_all_equivalent = False;
    return is_all_equivalent
    